using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Consts;
using AvalonAdmin.Helpers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using AvalonAdminDto.CarParts.CarPartsDtos;
using System.Linq;
using AvalonAdminDto.CarType.BrandDtos;
using AvalonAdminDto.CarType.VehicleSeriesDtos;
using AvalonAdmin.Pages.CarType.Views.VehicleSeries;
using D.UtilCore.Dtos;
using AvalonAdminDto.CarType.CarTypeVersionDtos;
using AvalonAdminDto.CarType.CarTypeDtos;
using AvalonAdminDto.Common;
using CommunityToolkit.Mvvm.Input;

namespace AvalonAdmin.Pages.CarType.ViewModels.CarTypeVersion
{
    public class CarTypeVersionModifyViewModel : BaseModifyViewModel
    {
        #region 私有字段
        private string? _id;
        
        private RepCarTypeVersion _currentCarTypeVersion;
        private RepBrand? _repBrand;
        private RepVehicleSeries? _repVehicleSeries;
        private RepCarType? _repCarType;
        #endregion

        #region 基础属性
        /// <summary>
        /// 当前ID
        /// </summary>
        public string? Id => _id; 
        #endregion

        #region 属性
        /// <summary>
        /// 当前车型版本
        /// </summary>
        public RepCarTypeVersion CurrentCarTypeVersion
        {
            get => _currentCarTypeVersion;
            set { _currentCarTypeVersion = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 销售名称
        /// </summary>
        public string? SalesName 
        { 
            get => CurrentCarTypeVersion?.SalesName;
            set 
            { 
                if (CurrentCarTypeVersion != null) 
                {
                    CurrentCarTypeVersion.SalesName = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 编码
        /// </summary>
        public string? Code 
        { 
            get => CurrentCarTypeVersion?.Code;
            set 
            { 
                if (CurrentCarTypeVersion != null) 
                {
                    CurrentCarTypeVersion.Code = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 版本
        /// </summary>
        public string? Version 
        { 
            get => CurrentCarTypeVersion?.Version;
            set 
            { 
                if (CurrentCarTypeVersion != null) 
                {
                    CurrentCarTypeVersion.Version = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 品牌
        /// </summary>
        public string? Brand
        {
            get => _repBrand?.Name;
            set { OnPropertyChanged(); }
        }

        /// <summary>
        /// 车系
        /// </summary>
        public string? VehicleSeries
        {
            get => _repVehicleSeries?.Name;
            set { OnPropertyChanged(); }
        }

        /// <summary>
        /// 车型
        /// </summary>
        public string? CarType
        {
            get => _repCarType?.Name;
            set { OnPropertyChanged(); }
        }

        /// <summary>
        /// 配件列表
        /// </summary>
        public ObservableCollection<RepCarPartsCarTypeVersion> RepCarPartsList { get; set; } = new();
        #endregion

        #region 构造函数
        public CarTypeVersionModifyViewModel(string? id, ViewStatus? viewStatus)
        {
            _id = id;
            SetupFormStatus(viewStatus);
            _currentCarTypeVersion = new RepCarTypeVersion();
            if (!string.IsNullOrEmpty(id))
            {
                _ = Task.Run(async () => await QueryAsync());
            }
        }
        
        #endregion

        #region 数据查询
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        public override async Task<bool> QueryAsync()
        {
            try
            {
                if (string.IsNullOrEmpty(Id)) return false;

                var response = await HttpHelper<RepCarTypeVersion>.GetAsync($"{ApiUrl.GetCarTypeVersion}/{Id}");
                
                if (response?.Code == StatusCodeEnum.OK && response.Data != null)
                {
                    CurrentCarTypeVersion = response.Data;
                    
                    // 加载关联数据
                    await LoadRelatedDataAsync(response.Data);
                    
                    // 加载配件列表
                    await LoadCarPartsListAsync(response.Data);
                    return true;
                }
                else if (response?.Code == StatusCodeEnum.Waring)
                {
                    ShowError(response.Msg);
                    return false;
                }
                else
                {
                    ShowError("服务器异常");
                    return false;
                }
            }
            catch (Exception ex)
            {
                ShowError($"加载数据失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 加载关联数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private async Task LoadRelatedDataAsync(RepCarTypeVersion data)
        {
            // 加载品牌信息
            var resBrand = await HttpHelper<RepBrand>.GetAsync($"{ApiUrl.GetBrand}/{data.BrandId}");
            _repBrand = resBrand.Data;
            
            // 加载车系信息
            var resVehicleSeries = await HttpHelper<RepVehicleSeries>.GetAsync($"{ApiUrl.GetVehicleSeries}/{data.VehicleSeriesId}");
            _repVehicleSeries = resVehicleSeries.Data;
            
            // 加载车型信息
            var resCarType = await HttpHelper<RepCarType>.GetAsync($"{ApiUrl.GetCarType}/{data.CarTypeId}");
            _repCarType = resCarType.Data;
            
            // 通知属性更新
            OnPropertyChanged(nameof(Brand));
            OnPropertyChanged(nameof(VehicleSeries));
            OnPropertyChanged(nameof(CarType));
        }

        /// <summary>
        /// 加载配件列表
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private async Task LoadCarPartsListAsync(RepCarTypeVersion data)
        {
            RepCarPartsList.Clear();
            
            // 获取已删除的配件ID列表
            List<string> deletedCarPartsList = data.CarPartsCarTypeVersionList
                .Where(a => a.State == 2)
                .Select(a => a.Id)
                .ToList();

            // 加载车型对应的配件
            var resRepCarType = await HttpHelper<List<RepCarParts>>.GetAsync($"{ApiUrl.GetCarPartsByCarTypeId}/{data.CarTypeId}");
            if (resRepCarType?.Data != null)
            {
                resRepCarType.Data.ForEach(carPart => {
                    RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                    {
                        CarPartsTypeName = carPart.VehicleSeriesCarPartsTypeEntityName,
                        Name = carPart.Name,
                        Code = carPart.Code,
                        Id = carPart.Id,
                        State = deletedCarPartsList.Contains(carPart.Id) ? 2 : -1,
                        Type = 1,
                        IsSelected = false
                    });
                });
            }

            // 加载新增的配件
            List<RepCarPartsCarTypeVersion> addCarPartsList = data.CarPartsCarTypeVersionList
                .Where(a => a.State == 0)
                .ToList();
                
            addCarPartsList.ForEach(carPart =>
            {
                RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                {
                    CarPartsTypeName = carPart.CarPartsTypeName,
                    Name = carPart.Name,
                    Id = carPart.Id,
                    Code = carPart.Code,
                    State = 0,
                    Type = 2
                });
            });
        }

        /// <summary>
        /// 加载数据方法
        /// </summary>
        protected async void LoadData()
        {
            await QueryAsync();
        }
        #endregion

        #region 提交保存
        /// <summary>
        /// 提交
        /// </summary>
        protected override async Task SubmitAsync()
        {
            try
            {
                // 基础数据验证
                if (string.IsNullOrEmpty(SalesName))
                {
                    ShowWarning("销售名称不可为空");
                    return;
                }

                // 构建配件版本列表
                List<CarPartsCarTypeVersion> carPartsCarTypeVersionList = new List<CarPartsCarTypeVersion>();
                
                // 处理删除的配件
                var deleteList = RepCarPartsList.Where(a => a.Type == 1 && a.State == 2);
                foreach (var item in deleteList)
                {
                    carPartsCarTypeVersionList.Add(new CarPartsCarTypeVersion()
                    {
                        CarPartsId = item.Id,
                        SerialNumber = -1,
                        State = 2
                    });
                }

                // 处理新增的配件
                var addList = RepCarPartsList.Where(a => a.Type == 2 && a.State == 0);
                int serialNumber = 0;
                foreach (var item in addList)
                {
                    serialNumber++;
                    carPartsCarTypeVersionList.Add(new CarPartsCarTypeVersion()
                    {
                        CarPartsId = item.Id,
                        SerialNumber = serialNumber,
                        State = 0
                    });
                }

                // 提交数据
                ApiResult<string> response;
                if (string.IsNullOrEmpty(Id))
                {
                    // 新增
                    var addRequest = new ReqAddCarTypeVersion
                    {
                        BrandId = _repBrand?.Id,
                        VehicleSeriesId = _repVehicleSeries?.Id,
                        CarTypeId = _repCarType?.Id,
                        Code = Code,
                        Version = Version,
                        SalesName = SalesName,
                        CarPartsCarTypeVersionList = carPartsCarTypeVersionList
                    };
                    response = await HttpHelper<string>.PostAsync(ApiUrl.AddCarTypeVersion, addRequest);
                }
                else
                {
                    // 修改
                    var updateRequest = new ReqUpdateCarTypeVersion
                    {
                        Id = Id,
                        BrandId = _repBrand?.Id,
                        VehicleSeriesId = _repVehicleSeries?.Id,
                        CarTypeId = _repCarType?.Id,
                        Code = Code,
                        Version = Version,
                        SalesName = SalesName,
                        CarPartsCarTypeVersionList = carPartsCarTypeVersionList
                    };
                    response = await HttpHelper<string>.PutAsync(ApiUrl.UpdateCarTypeVersion, updateRequest);
                }

                // 处理响应
                if (response.Code == StatusCodeEnum.OK)
                {
                    ShowSuccess(response.Msg);
                    CloseDialog();
                }
                else
                {
                    ShowError(response.Msg);
                }
            }
            catch (Exception ex)
            {
                ShowError($"保存失败: {ex.Message}");
            }
        }
        #endregion

        #region 选择操作
        /// <summary>
        /// 获取品牌、车系、车型
        /// </summary>
        /// <param name="obj"></param>
        protected void Get(object? obj)
        {
            if (obj == null) return;

            string type = obj.ToString();
            switch (type)
            {
                case "Brand":
                    OpenBrandQuery();
                    break;
                case "VehicleSeries":
                    OpenVehicleSeriesQuery();
                    break;
                case "CarType":
                    OpenCarTypeQuery();
                    break;
            }
        }

        /// <summary>
        /// 打开品牌查询
        /// </summary>
        private async void OpenBrandQuery()
        {
            // TODO: 实现品牌查询功能
            // var brandQuery = new Page_Brand_Query();
            // var viewModel = (BrandQueryViewModel)brandQuery.DataContext;
            // BrandQueryViewModel没有InformationRequested事件，需要其他方式处理
            // await brandQuery.ShowDialog(null);
        }

        /// <summary>
        /// 打开车系查询
        /// </summary>
        private async void OpenVehicleSeriesQuery()
        {
            if (string.IsNullOrWhiteSpace(Brand))
            {
                ShowWarning("品牌不可为空");
                return;
            }

            // Todo
            //var vehicleSeriesQuery = new Page_VehicleSeries_Query(_repBrand?.Id);
            //var viewModel = (VehicleSeriesQueryViewModel)vehicleSeriesQuery.DataContext;
            //viewModel.InformationRequested += VehicleSeries_InformationRequested;
            //await vehicleSeriesQuery.ShowDialog(null);
        }

        /// <summary>
        /// 打开车型查询
        /// </summary>
        private void OpenCarTypeQuery()
        {
            if (string.IsNullOrWhiteSpace(VehicleSeries))
            {
                ShowWarning("车系不可为空");
                return;
            }

            // TODO: 实现车型查询功能
            // var carTypeQuery = new Page_CarType_Query(_repVehicleSeries?.Id);
            // var viewModel = carTypeQuery.DataContext;
            // viewModel.InformationRequested += CarType_InformationRequested;
        }
        #endregion

        #region 事件处理
        /// <summary>
        /// 品牌选择事件
        /// </summary>
        private void Brand_InformationRequested(object sender, InformationEventArgs<RepBrand> e)
        {
            _repBrand = e.Information;
            OnPropertyChanged(nameof(Brand));
        }

        /// <summary>
        /// 车系选择事件
        /// </summary>
        private void VehicleSeries_InformationRequested(object sender, EventArgs e)
        {
            if (e is InformationRequestedEventArgs args && args.SelectedModel is RepVehicleSeries vehicleSeries)
            {
                _repVehicleSeries = vehicleSeries;
                OnPropertyChanged(nameof(VehicleSeries));
            }
        }

        /// <summary>
        /// 车型选择事件
        /// </summary>
        private async void CarType_InformationRequested(object sender, InformationEventArgs<RepCarType> e)
        {
            _repCarType = e.Information;
            OnPropertyChanged(nameof(CarType));
            
            // 重新加载配件列表
            RepCarPartsList.Clear();
            if (!string.IsNullOrEmpty(_repCarType?.Id))
            {
                var response = await HttpHelper<List<RepCarParts>>.GetAsync($"{ApiUrl.GetCarPartsByCarTypeId}/{_repCarType.Id}");
                if (response?.Data != null)
                {
                    response.Data.ForEach(carPart => {
                        RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                        {
                            CarPartsTypeName = carPart.VehicleSeriesCarPartsTypeEntityName,
                            Name = carPart.Name,
                            Code = carPart.Code,
                            State = -1,
                            Type = 1
                        });
                    });
                }
            }
        }
        #endregion

        #region 配件管理
        /// <summary>
        /// 新增配件
        /// </summary>
        protected async void Add(object? obj)
        {
            if (string.IsNullOrWhiteSpace(VehicleSeries))
            {
                ShowWarning("车系不可为空");
                return;
            }
            // Todo
            //var carPartsQuery = new Page_CarParts_Query(null, _repVehicleSeries.Id);
            //var viewModel = (CarPartsQueryViewModel)carPartsQuery.DataContext;
            //viewModel.InformationRequested += CarParts_InformationRequested;
            //await carPartsQuery.ShowDialog(null);
        }

        /// <summary>
        /// 配件选择事件
        /// </summary>
        private void CarParts_InformationRequested(object sender, EventArgs e)
        {
            if (e is InformationRequestedEventArgs args && args.SelectedModel is List<RepCarParts> carPartsList)
            {
                List<string> existingCarPartsIds = RepCarPartsList.Select(a => a.Id).ToList();
                List<RepCarParts> newCarParts = carPartsList.Where(a => !existingCarPartsIds.Contains(a.Id)).ToList();
                
                newCarParts.ForEach(carPart => {
                    RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                    {
                        CarPartsTypeName = carPart.VehicleSeriesCarPartsTypeEntityName,
                        Id = carPart.Id,
                        Name = carPart.Name,
                        Code = carPart.Code,
                        State = 0,
                        Type = 2
                    });
                });
            }
        }

        /// <summary>
        /// 批量删除配件
        /// </summary>
        protected void BatchDelete(object? obj)
        {
            var newCarPartsList = new ObservableCollection<RepCarPartsCarTypeVersion>();
            
            foreach (var carTypeVersion in RepCarPartsList)
            {
                if (carTypeVersion.IsSelected && carTypeVersion.Type == 1)
                {
                    carTypeVersion.State = 2;
                }
                newCarPartsList.Add(carTypeVersion);
            }
            
            RepCarPartsList = newCarPartsList;
        }

        /// <summary>
        /// 还原按钮启用状态
        /// </summary>
        private bool _restoreBtnEnabled = true;
        public bool RestoreBtnEnabled
        {
            get => _restoreBtnEnabled;
            set => SetProperty(ref _restoreBtnEnabled, value);
        }

        /// <summary>
        /// 还原命令
        /// </summary>
        private RelayCommand<object?>? _restoreCommand;
        public RelayCommand<object?> RestoreCommand => _restoreCommand ??= new RelayCommand<object?>(Restore);

        /// <summary>
        /// 还原配件
        /// </summary>
        protected void Restore(object? obj)
        {
            if (obj is not RepCarPartsCarTypeVersion selectCarParts) return;

            var newCarPartsList = new ObservableCollection<RepCarPartsCarTypeVersion>();
            
            foreach (var carTypeVersion in RepCarPartsList)
            {
                if (carTypeVersion.Id == selectCarParts.Id)
                {
                    carTypeVersion.State = null;
                }
                newCarPartsList.Add(carTypeVersion);
            }
            
            RepCarPartsList = newCarPartsList;
        }
        #endregion

        #region 重置表单
        /// <summary>
        /// 重置表单
        /// </summary>
        protected override void Reset()
        {
            // 重置当前车型版本数据
            CurrentCarTypeVersion = new RepCarTypeVersion();
            _repBrand = null;
            _repVehicleSeries = null;
            _repCarType = null;
        }
        #endregion
    }
}


